package com.baizhi.controller;

import com.baizhi.common.dto.Product;
import com.baizhi.common.enums.AckCode;
import com.baizhi.common.vo.PageVO;
import com.baizhi.common.vo.R;
import com.baizhi.feign.ProductFeignClient;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 负载均衡方法，解决nacos服务列表选择问题
 */
@RestController
public class UserFeignController {

    private static final Logger log = LoggerFactory.getLogger(UserFeignController.class);


    /**
     * feign代理
     */
    @Autowired
    private ProductFeignClient productFeignClient;

    /**
     * 使用load balance框架来实现服务选择
     * @param userId
     * @return
     * @throws JsonProcessingException
     */
    @GetMapping("/feign/user/{userId}")
    public R feignSearch(@PathVariable(value = "userId") int userId) throws JsonProcessingException {
        log.info("user  demo....");

        Map<String, Object> params = new HashMap<>();
        params.put("userId", userId);
        params.put("userName", "小张");


        // 下面的代码太复杂了,能不能简化，使用openfeign来解决
        R<PageVO<Product>> forObject = this.productFeignClient.productSearch(1, 5, null);

        if (forObject != null && forObject.getCode() == AckCode.SUCCESS.getCode()) {
            params.put("data", forObject.getData());
            return  R.okHasData(params);
        } else {
            return forObject;
        }
    }





}
